﻿using System.IO;
using System.Windows;
using Microsoft.Win32.TaskScheduler;

namespace DesktopToyWpf.Services;

/// <summary>
/// 使用计划任务管理程序开机启动
/// </summary>
public static class TaskSchedulerStartupManager
{
    private const string TaskName = "DesktopToyWpfStartup";

    /// <summary>
    /// 设置或取消程序开机启动
    /// </summary>
    /// <param name="enable">是否启用开机启动</param>
    /// <returns>操作是否成功</returns>
    public static bool SetStartup(bool enable)
    {
        try
        {
            var appPath = System.Diagnostics.Process.GetCurrentProcess().MainModule?.FileName;

            // 验证程序路径是否有效
            if (!File.Exists(appPath))
            {
                throw new FileNotFoundException("程序路径不存在", appPath);
            }

            using var ts = new TaskService();

            if (enable)
            {
                // 创建开机启动任务
                var td = ts.NewTask();
                td.RegistrationInfo.Description = $"{Global.AppName} Application Startup";
                td.Principal.RunLevel = TaskRunLevel.Highest; // 以最高权限运行

                // 设置触发器：用户登录时
                td.Triggers.Add(new LogonTrigger());

                // 设置动作：启动程序
                td.Actions.Add(new ExecAction(appPath));

                // 注册任务
                ts.RootFolder.RegisterTaskDefinition(TaskName, td);
            }
            else
            {
                // 删除开机启动任务
                if (ts.RootFolder.Tasks.Exists(TaskName))
                {
                    ts.RootFolder.DeleteTask(TaskName);
                }
            }

            return true;
        }
        catch (Exception ex)
        {
            MessageBox.Show($"设置开机启动失败: {ex.Message}");
            return false;
        }
    }

    /// <summary>
    /// 检查程序是否已设置开机启动
    /// </summary>
    /// <returns>是否已设置开机启动</returns>
    public static bool IsStartupEnabled()
    {
        try
        {
            using var ts = new TaskService();
            return ts.RootFolder.Tasks.Exists(TaskName);
        }
        catch
        {
            return false;
        }
    }
}